package com.elder.business.service.impl;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import com.alibaba.fastjson2.JSONObject;
import com.elder.business.domain.EgressRegisterRecords;
import com.elder.business.domain.ElderlyInfo;
import com.elder.business.domain.RetreatRecordsVO;
import com.elder.business.mapper.ElderlyInfoMapper;
import com.elder.business.mapper.ElderlyapartmentMapper;
import com.elder.common.core.page.TableDataInfo;
import com.elder.common.enums.ApplyStatus;
import com.elder.common.utils.DateUtils;
import com.elder.common.utils.LongUtils;
import com.elder.common.utils.StringNewUtils;
import com.elder.common.utils.bean.BeanUtils;
import com.elder.common.utils.uuid.SnowGenerator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.elder.business.mapper.RetreatRecordsMapper;
import com.elder.business.domain.RetreatRecords;
import com.elder.business.service.IRetreatRecordsService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 老人退住Service业务层处理
 * 
 * @author elder
 * @date 2023-11-26
 */
@Service
public class RetreatRecordsServiceImpl implements IRetreatRecordsService 
{
    @Autowired
    private RetreatRecordsMapper retreatRecordsMapper;
    @Autowired
    private ElderlyInfoMapper elderlyInfoMapper;
    @Autowired
    private ElderlyapartmentMapper elderlyapartmentMapper;

    /**
     * 查询老人退住
     * 
     * @param id 老人退住主键
     * @return 老人退住
     */
    @Override
    public JSONObject selectRetreatRecordsById(Long id)
    {
        RetreatRecords v = retreatRecordsMapper.selectRetreatRecordsById(id);
        ElderlyInfo elder = elderlyInfoMapper.getElderInfoByElderId(v.getElderId());
        JSONObject obj = new JSONObject();
        obj.put("id", StringNewUtils.formatStr(v.getId()));
        obj.put("elderId", StringNewUtils.formatStr(v.getElderId()));
        obj.put("elderName", Objects.isNull(elder)?"":elder.getElderName());
        obj.put("retreatTime", DateUtils.dateStrMIAO(v.getRetreatTime()));
        obj.put("retreatReason", v.getRetreatReason());
        obj.put("applyTime", DateUtils.dateStrMIAO(v.getApplyTime()));
        obj.put("auditTime", DateUtils.dateStrMIAO(v.getAuditTime()));
        obj.put("auditPerson", v.getAuditPerson());
        obj.put("elderRelationship", v.getElderRelationship());
        obj.put("applicant", v.getApplicant());
        return obj;
    }

    /**
     * 查询老人退住列表
     * 
     * @param retreatRecords 老人退住
     * @return 老人退住
     */
    @Override
    public List<RetreatRecords> selectRetreatRecordsList(RetreatRecords retreatRecords)
    {
        return retreatRecordsMapper.selectRetreatRecordsList(retreatRecords);
    }

    /**
     * 新增老人退住
     * 
     * @param retreatRecords 老人退住
     * @return 结果
     */
    @Override
    public int insertRetreatRecords(RetreatRecordsVO retreatRecords)
    {
        RetreatRecords retreat = new RetreatRecords();
        BeanUtils.copyProperties(retreatRecords,retreat);
        retreat.setId(SnowGenerator.getId());
        retreat.setElderId(LongUtils.str2Long(retreatRecords.getElderId()));
        retreat.setApplyTime(DateUtils.getLongTime());
        retreat.setStatus(ApplyStatus.APPLUING.getValue());
        retreat.setRetreatTime(DateUtils.getDateSeconds(retreatRecords.getRetreatTime()));
        retreat.setCreateTime(DateUtils.getLongTime());
        return retreatRecordsMapper.insertRetreatRecords(retreat);
    }

    /**
     * 修改老人退住
     * 
     * @param retreatRecords 老人退住
     * @return 结果
     */
    @Override
    public int updateRetreatRecords(RetreatRecordsVO retreatRecords)
    {
        RetreatRecords retreat = new RetreatRecords();
        BeanUtils.copyProperties(retreatRecords,retreat);
        retreat.setId(LongUtils.str2Long(retreatRecords.getId()));
        retreat.setElderId(LongUtils.str2Long(retreatRecords.getElderId()));
        retreat.setRetreatTime(DateUtils.getDateSeconds(retreatRecords.getRetreatTime()));
        retreat.setAuditTime(DateUtils.getLongTime());
        retreat.setUpdateTime(DateUtils.getLongTime());
        return retreatRecordsMapper.updateRetreatRecords(retreat);
    }

    /**
     * 批量删除老人退住
     * 
     * @param ids 需要删除的老人退住主键
     * @return 结果
     */
    @Override
    public int deleteRetreatRecordsByIds(Long[] ids)
    {
        return retreatRecordsMapper.deleteRetreatRecordsByIds(ids);
    }

    /**
     * 删除老人退住信息
     * 
     * @param id 老人退住主键
     * @return 结果
     */
    @Override
    public int deleteRetreatRecordsById(Long id)
    {
        return retreatRecordsMapper.deleteRetreatRecordsById(id);
    }

    @Override
    public TableDataInfo getRetreatRecordsList(String elderName, String startTime, String endTime,String applyStatus, Integer pageNum, Integer pageSize) {
        List<Long> elderIds = null;
        if(!StringNewUtils.isEmpty(elderName)){
            List<ElderlyInfo> elderinfoList = elderlyInfoMapper.getElderinfoList(elderName);
            elderIds = elderinfoList.stream().map(ElderlyInfo::getElderId).collect(Collectors.toList());
        }
        Long startDayTime = null;
        Long endDayTime = null;
        if(!StringNewUtils.isEmpty(startTime) && !StringNewUtils.isEmpty(endTime)){
            Long dateStart = DateUtils.getTargetDateSeconds(startTime);
            Long dateEnd = DateUtils.getTargetDateSeconds(endTime);
            startDayTime = DateUtils.getDayStartTime(dateStart);
            endDayTime = DateUtils.getDayEndTime(dateEnd);
        }
        //获取分页数据
        PageHelper.startPage(pageNum,pageSize);
        List<RetreatRecords> list = retreatRecordsMapper.getRetreatRecordsList(elderIds,ApplyStatus.getValue(applyStatus),startDayTime,endDayTime);
        PageInfo<RetreatRecords> page = new PageInfo<>(list);
        List<RetreatRecords> recordsList = page.getList();
        //获取老人信息
        List<Long> elderIdList = recordsList.stream().map(RetreatRecords::getElderId).collect(Collectors.toList());
        List<ElderlyInfo> elderlyInfoList = elderlyInfoMapper.getElderInfoByElderIds(elderIdList);
        Map<Long, String> elderMap = elderlyInfoList.stream().collect(Collectors.toMap(ElderlyInfo::getElderId, ElderlyInfo::getElderName));
        List<JSONObject> datalist = recordsList.stream().map(v -> {
            JSONObject obj = new JSONObject();
            obj.put("id", StringNewUtils.formatStr(v.getId()));
            obj.put("elderId", StringNewUtils.formatStr(v.getElderId()));
            obj.put("elderName", elderMap.get(v.getElderId()));
            obj.put("retreatTime", DateUtils.dateStrMIAO(v.getRetreatTime()));
            obj.put("retreatReason", v.getRetreatReason());
            obj.put("applyTime", DateUtils.dateStrMIAO(v.getApplyTime()));
            obj.put("auditTime", DateUtils.dateStrMIAO(v.getAuditTime()));
            obj.put("auditPerson", v.getAuditPerson());
            obj.put("elderRelationship", v.getElderRelationship());
            obj.put("applicant", v.getApplicant());
            return obj;
        }).collect(Collectors.toList());
        TableDataInfo result = new TableDataInfo();
        result.setCode(200);
        result.setMsg("success");
        result.setTotal(page.getTotal());
        result.setRows(datalist);
        return result;
    }

    @Override
    public int delRetreatRecordsByIds(Long[] ids) {
        return retreatRecordsMapper.upRetreatRecordsById(ids);
    }

    @Override
    @Transactional
    public int updateEgressRegisterApprove(Long id,Long elderId, String applyStatus) {
        //如果申请退住通过更新公寓入住人数
        if(Objects.equals(applyStatus,ApplyStatus.APPLY_PASS.getDisplayName())){
            ElderlyInfo elderlyInfo = elderlyInfoMapper.getElderInfoByElderId(elderId);
            elderlyapartmentMapper.updateElderlyapartmentLiveNum(elderlyInfo.getApartmentId(),-1);
            //清楚入住信息

            //计算退住 所剩金额
        }
        return retreatRecordsMapper.updateEgressRegisterApprove(id, ApplyStatus.getValue(applyStatus));
    }
}
